package com.freedom.ums.member.application.service.cmd;

import com.freedom.common.core.constant.RedisConstants;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@RequiredArgsConstructor
public class InviteCodeCmdService {

    private final RedissonClient redissonClient;

    private static final int QUEUE_COUNT = 64;

    /**
     * 邀请码hash轮训的key
     */
    private static final String ID_KEY = RedisConstants.INVITE_CODE_ID;

    /**
     * 邀请码queue的key
     *
     */
    private static final String QUEUE_PREFIX = RedisConstants.INVITE_CODE_Q;

    private RScript rScript;

    private String inviteCodeLua;

    @PostConstruct
    void init() {
        rScript = redissonClient.getScript(StringCodec.INSTANCE);
        inviteCodeLua =
                rScript.scriptLoad(
                        "local id=redis.call('get', '" + ID_KEY + "');" +
                                "id=(id+1)%" + QUEUE_COUNT + ";" +
                                "redis.call('set','" + ID_KEY + "',id);" +
                                "return redis.call('lpop', '" + QUEUE_PREFIX + "'..id);"
                );
    }

    /** 取出一个邀请码 */
    public String fetchOne() {
        return rScript.evalSha(RScript.Mode.READ_WRITE, inviteCodeLua, RScript.ReturnType.VALUE);
    }
}
